# -*- coding:utf-8 -*-

import redis
from config import Config
import ast

config = Config()

class Operator(object):
	
	def __init__(self, host=config.REDIS_HOST, port=config.REDIS_PORT):
		self.r = redis.Redis(host=host, port=port)
	
	def get(self, key):				#获取key对应的value
		return self.r.get(key)

	def hget(self, key, filed):			#获取key中field的值
		return self.r.hget(key, filed)

	def set(self, key, value):			#设置key的值
		return self.r.set(key, value)

	def lpush(self, key, value):			#设置key的值
		return self.r.lpush(key, value)

	def lrem(self, key, count, value):		#移除值
		return self.r.lrem(key, count, value)

	def hset(self, key, filed, value):		#设置key中filed的值
		return self.r.hset(key, filed, value)

	def hsetall(self, key, kws):			#传入一个字典，批量设置key的值
		for k, v in kws.items():
			self.r.hset(key, k, v)
		return True

	def hgetall(self, key):				#获取key的值，返回一个字典
		return self.r.hgetall(key)

	def delete(self, key):				#删除key	
		return self.r.delete(key)

	def hincrby(self, key, field):			#将key中field的值加一
		return self.r.hincrby(key, field)

	# 车辆属性用到
	def all(self, key):
		ks = self.hgetall(key)
		d = {}
		for k in ks:
			try:
				v =  ast.literal_eval(self.hget(key, k))
				d[k] = v
			except Exception as e:
				raise Exception(u'车辆属性数据结构错误', e)
		return d

	def flat_all(self, key):
		field = self.all(key)  # {"1": (value, sort)}  或 {}
		l = []
		for k, v in field.items():
			d = {}
			value, sort = v
			d['id'] = k
			d['value'] = value
			d['sort'] = sort
			l.append(d)
		l.sort(key=lambda x: int(x['sort']))
		return l

	# l=[{'sort':'1','id':'3', 'value': 'xx'},{'sort':'3','id':'2', 'value': 'xx'},{'sort':'2','id':'1',  'value': 'xx'}]
